import type { FormInstance } from 'element-plus'
import type { FormValuesType, TemplatePropsType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElRow,
  ElCol,
  ElButton,
  ElIcon,
  ElMessage,
  ElInputNumber,
  ElSelect,
  ElOption,
  ElCascader
} from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent({
  name: 'SystemUserOptions',
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: TemplatePropsType, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const formValues = reactive<FormValuesType>({})
    const dictState = useVuexGetters('dict', ['tenantSeleceOpt'])
    const state = reactive({
      tenantDictTreeOpt: []
    })
    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 提交表单
    const handleSubmitForm = () => {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validate(async (valid) => {
        if (!valid) return
        const params = { ...formValues }
        const res = await store.dispatch('dict/TenantDictSubmitPost', params)
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleCloseModal()
        }
      })
    }
    //  选择租户
    const tenantIdChange = (value: string) => {
      dictState.tenantSeleceOpt?.value?.forEach((item: any) => {
        if (value === item.tenantId) {
          formValues.$tenantId = item.tenantName
        }
      })
    }
    //  上级tree
    const tenantDictTreeAjax = async () => {
      try {
        const { data } = await store.dispatch('dict/TenantDictTreeGet')
        state.tenantDictTreeOpt = data
      } catch (error) {}
    }
    onMounted(() => {
      const { type } = props
      if (props.record?.id) {
        Object.assign(
          formValues,
          type === 'update'
            ? {
                id: props.record?.id,
                code: props.record?.code,
                dictValue: props.record?.dictValue,
                dictKey: props.record?.dictKey,
                sort: props.record?.sort,
                remark: props.record?.remark,
                tenantId: props.record?.tenantId
              }
            : props.record
        )
      }
      if (type === 'add') {
        formValues.parentId = props.record.id
      }
      tenantDictTreeAjax()
    })

    return () => {
      const { type, visible } = props
      return (
        <ElDialog
          title={type === 'add' ? '新增' : '编辑'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <EditPen />
                    </ElIcon>
                    &nbsp; 保存
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>取消</ElButton>
                </>
              )
            }
          }
        >
          <ElForm label-width="100px" ref={ruleFormRef} model={formValues}>
            <ElRow>
              <ElCol span={24}>
                <ElFormItem
                  prop="code"
                  label="字典编号"
                  rules={[{ required: true, message: '请输入字典编号' }]}
                >
                  {type === 'read' ? (
                    formValues.code
                  ) : (
                    <ElInput
                      disabled={type === 'add'}
                      v-model={formValues.code}
                      placeholder="请输入字典编号"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={12}>
                <ElFormItem
                  prop="dictValue"
                  label="字典名称"
                  rules={[{ required: true, message: '请输入字典名称' }]}
                >
                  {type === 'read' ? (
                    formValues.dictValue
                  ) : (
                    <ElInput v-model={formValues.dictValue} placeholder="请输入字典名称" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={12}>
                <ElFormItem
                  prop="parentId"
                  label="上级字典"
                  rules={[{ required: true, message: '请输入上级字典', trigger: 'change' }]}
                >
                  {type === 'read' ? (
                    formValues.parentId
                  ) : (
                    <ElCascader
                      disabled={type === 'add'}
                      v-model={formValues.parentId}
                      options={state.tenantDictTreeOpt}
                      props={{
                        label: 'title',
                        emitPath: false,
                        checkStrictly: true
                      }}
                      show-all-levels={false}
                      placeholder="请输入上级字典"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={12}>
                <ElFormItem
                  prop="dictKey"
                  label="字典键值"
                  rules={[{ required: true, message: '请输入字典键值' }]}
                >
                  {type === 'read' ? (
                    formValues.dictKey
                  ) : (
                    <ElInputNumber
                      v-model={formValues.dictKey}
                      controls-position="right"
                      placeholder="请输入字典键值"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={12}>
                <ElFormItem
                  prop="sort"
                  label="字典排序"
                  rules={[{ required: true, message: '请输入字典排序' }]}
                >
                  {type === 'read' ? (
                    formValues.sort
                  ) : (
                    <ElInputNumber
                      v-model={formValues.sort}
                      controls-position="right"
                      placeholder="请输入字典排序"
                    />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={24}>
                <ElFormItem
                  prop="remark"
                  label="字典备注"
                  rules={[{ required: false, message: '请输入字典备注' }]}
                >
                  {type === 'read' ? (
                    formValues.remark
                  ) : (
                    <ElInput v-model={formValues.remark} placeholder="请输入字典备注" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol span={12}>
                <ElFormItem
                  prop="tenantId"
                  label="所属租户"
                  rules={[{ required: true, message: '请输入所属租户' }]}
                >
                  {type === 'read' ? (
                    formValues.tenantId
                  ) : (
                    <ElSelect
                      v-model={formValues.tenantId}
                      placeholder="所属租户"
                      clearable
                      disabled={type !== 'update'}
                      onChange={tenantIdChange}
                    >
                      {dictState.tenantSeleceOpt?.value?.map((item: any) => (
                        <ElOption
                          key={item?.tenantId}
                          label={item?.tenantName}
                          value={item?.tenantId!}
                        />
                      ))}
                    </ElSelect>
                  )}
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
        </ElDialog>
      )
    }
  }
})
